<template>
  <div>
    <shopCarHead
      :checkedAll="data.checkedAll"
      @setCheckedAll="setCheckedAll"
    />
    <shopCarMain :list="data.list" @changeNum="changeNum" @delitem="delitem" />
    <shopCarFoot :num="num" :price="price" />
  </div>
</template>

<script setup>
import shopCarHead from "@/components/ShopCar/head.vue";
import shopCarMain from "@/components/ShopCar/main.vue";
import shopCarFoot from "@/components/ShopCar/foot.vue";
import { ref, computed, watch } from "vue";
let data = ref({
  checkedAll: false,
  list: [
    {
      id: 1,
      goodsname: "商品一",
      goodsprice: 100,
      goodsnum: 1,
      checked: false,
    },
    {
      id: 2,
      goodsname: "商品二",
      goodsprice: 200,
      goodsnum: 2,
      checked: false,
    },
    {
      id: 3,
      goodsname: "商品三",
      goodsprice: 300,
      goodsnum: 3,
      checked: false,
    },
  ],
});
const changeNum = ({ item, num }) => {
  item.goodsnum = item.goodsnum + num;
};
const delitem = (id) => {
  data.value.list = data.value.list.filter((item) => item.id !== id);
};
const setCheckedAll = (flag) => {
  data.value.list.forEach((item) => {
    item.checked = flag;
  });
};
let price = computed(() => {
  let checkList = data.value.list.filter((item) => item.checked);
  if (checkList.length) {
    return checkList
      .map((item) => item.goodsnum * item.goodsprice)
      .reduce((a, b) => a + b);
  }
  return 0;
});

let num = computed(() => {
  //计算属性
  let checkedList = data.value.list.filter((item) => item.checked);
  if (checkedList.length) {
    return checkedList.map((item) => item.goodsnum).reduce((a, b) => a + b);
  }
  return 0;
});

watch(
  [data],
  () => {
    data.value.checkedAll = data.value.list.length
      ? data.value.list.every((item) => item.checked)
      : false;
  },
  { deep: true }
); //深度监听
</script>

<style>
.table {
  width: 100%;
}
.tr {
  display: flex;
}
.tr .td {
  flex: 1;
  text-align: center;
  line-height: 40px;
  color: black;
}
</style>
